# -*- coding: utf-8 -*-
from application import app, db
from common.libs.Helper import getCurrentDate, getFormatDate
from common.models.stat.StatDailyFood import StatDailyFood
from common.models.stat.StatDailyMember import StatDailyMember
from common.models.stat.StatDailySite import StatDailySite
from common.models.pay.PayOrder import PayOrder
from common.models.pay.PayOrderItem import PayOrderItem
from common.models.food.FoodSaleChangeLog import FoodSaleChangeLog
from common.models.member.Member import Member
from common.models.food.WxShareHistory import WxShareHistory
from sqlalchemy import func
import datetime

class StatService:
    def __init__(self):
        pass

    def updateOrderStats(self, pay_order_id):
        """订单完成后更新统计数据"""
        try:
            pay_order_info = PayOrder.query.filter_by(id=pay_order_id).first()
            if not pay_order_info:
                return False

            # 获取订单日期
            order_date = pay_order_info.created_time.date()
            date_str = order_date.strftime("%Y-%m-%d")
            
            app.logger.info(f"开始更新订单 {pay_order_id} 的统计数据，日期: {date_str}")
            
            # 更新商品统计
            self.updateFoodStats(pay_order_id, date_str)
            
            # 更新会员统计
            self.updateMemberStats(pay_order_info.member_id, date_str)
            
            # 更新站点统计
            self.updateSiteStats(date_str)
            
            app.logger.info(f"订单 {pay_order_id} 的统计数据更新完成")
            return True
            
        except Exception as e:
            app.logger.error(f"更新订单 {pay_order_id} 统计数据失败: {str(e)}")
            return False

    def updateFoodStats(self, pay_order_id, date_str):
        """更新商品统计数据"""
        try:
            # 获取订单商品
            pay_order_items = PayOrderItem.query.filter_by(pay_order_id=pay_order_id).all()
            
            # 按商品ID汇总数据，避免重复计算
            food_summary = {}
            for item in pay_order_items:
                if item.food_id not in food_summary:
                    food_summary[item.food_id] = {
                        'total_count': 0,
                        'total_amount': 0.0
                    }
                food_summary[item.food_id]['total_count'] += item.quantity
                food_summary[item.food_id]['total_amount'] += float(item.price) * item.quantity
            
            # 更新或创建统计数据
            for food_id, summary in food_summary.items():
                # 检查是否已存在该商品的统计数据
                stat_food = StatDailyFood.query.filter_by(
                    date=datetime.datetime.strptime(date_str, "%Y-%m-%d").date(),
                    food_id=food_id
                ).first()
                
                if stat_food:
                    # 更新现有记录（重新计算，避免累加错误）
                    stat_food.total_count = summary['total_count']
                    stat_food.total_pay_money = summary['total_amount']
                    stat_food.updated_time = getCurrentDate()
                else:
                    # 创建新记录
                    stat_food = StatDailyFood()
                    stat_food.date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
                    stat_food.food_id = food_id
                    stat_food.total_count = summary['total_count']
                    stat_food.total_pay_money = summary['total_amount']
                    stat_food.created_time = getCurrentDate()
                    stat_food.updated_time = getCurrentDate()
                
                db.session.add(stat_food)
            
            db.session.commit()
            app.logger.info(f"商品统计数据更新完成，订单ID: {pay_order_id}")
            
        except Exception as e:
            db.session.rollback()
            app.logger.error(f"更新商品统计数据失败: {str(e)}")
            raise

    def updateMemberStats(self, member_id, date_str):
        """更新会员统计数据"""
        try:
            # 检查是否已存在该会员的统计数据
            stat_member = StatDailyMember.query.filter_by(
                date=datetime.datetime.strptime(date_str, "%Y-%m-%d").date(),
                member_id=member_id
            ).first()
            
            # 计算该会员当日的消费总额
            date_from = date_str + " 00:00:00"
            date_to = date_str + " 23:59:59"
            
            total_pay = db.session.query(func.sum(PayOrder.total_price).label("total_pay_money")) \
                .filter(PayOrder.member_id == member_id, PayOrder.status == 1) \
                .filter(PayOrder.created_time >= datetime.datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S"),
                       PayOrder.created_time <= datetime.datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S")) \
                .first()
            
            # 计算该会员当日的分享次数
            total_share = WxShareHistory.query.filter(WxShareHistory.member_id == member_id) \
                .filter(WxShareHistory.created_time >= datetime.datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S"),
                       WxShareHistory.created_time <= datetime.datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S")) \
                .count()
            
            if stat_member:
                # 更新现有记录
                stat_member.total_pay_money = total_pay[0] if total_pay[0] else 0.00
                stat_member.total_shared_count = total_share
                stat_member.updated_time = getCurrentDate()
            else:
                # 创建新记录
                stat_member = StatDailyMember()
                stat_member.date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
                stat_member.member_id = member_id
                stat_member.total_pay_money = total_pay[0] if total_pay[0] else 0.00
                stat_member.total_shared_count = total_share
                stat_member.created_time = getCurrentDate()
                stat_member.updated_time = getCurrentDate()
            
            db.session.add(stat_member)
            db.session.commit()
            app.logger.info(f"会员统计数据更新完成，会员ID: {member_id}")
            
        except Exception as e:
            db.session.rollback()
            app.logger.error(f"更新会员统计数据失败: {str(e)}")
            raise

    def updateSiteStats(self, date_str):
        """更新站点统计数据"""
        try:
            # 检查是否已存在该日期的站点统计数据
            stat_site = StatDailySite.query.filter_by(
                date=datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
            ).first()
            
            date_from = date_str + " 00:00:00"
            date_to = date_str + " 23:59:59"
            
            # 计算当日营收
            stat_pay = db.session.query(func.sum(PayOrder.total_price).label("total_pay_money")) \
                .filter(PayOrder.status == 1) \
                .filter(PayOrder.created_time >= datetime.datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S"),
                       PayOrder.created_time <= datetime.datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S")) \
                .first()
            
            # 计算会员总数
            stat_member_count = Member.query.count()
            
            # 计算当日新增会员数
            stat_new_member_count = Member.query.filter(
                Member.created_time >= datetime.datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S"),
                Member.created_time <= datetime.datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S")
            ).count()
            
            # 计算当日订单数
            stat_order_count = PayOrder.query.filter_by(status=1) \
                .filter(PayOrder.created_time >= datetime.datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S"),
                       PayOrder.created_time <= datetime.datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S")) \
                .count()
            
            # 计算当日分享数
            stat_share_count = WxShareHistory.query.filter(
                WxShareHistory.created_time >= datetime.datetime.strptime(date_from, "%Y-%m-%d %H:%M:%S"),
                WxShareHistory.created_time <= datetime.datetime.strptime(date_to, "%Y-%m-%d %H:%M:%S")
            ).count()
            
            if stat_site:
                # 更新现有记录
                stat_site.total_pay_money = stat_pay[0] if stat_pay[0] else 0.00
                stat_site.total_member_count = stat_member_count
                stat_site.total_new_member_count = stat_new_member_count
                stat_site.total_order_count = stat_order_count
                stat_site.total_shared_count = stat_share_count
                stat_site.updated_time = getCurrentDate()
            else:
                # 创建新记录
                stat_site = StatDailySite()
                stat_site.date = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
                stat_site.total_pay_money = stat_pay[0] if stat_pay[0] else 0.00
                stat_site.total_member_count = stat_member_count
                stat_site.total_new_member_count = stat_new_member_count
                stat_site.total_order_count = stat_order_count
                stat_site.total_shared_count = stat_share_count
                stat_site.created_time = getCurrentDate()
                stat_site.updated_time = getCurrentDate()
            
            db.session.add(stat_site)
            db.session.commit()
            app.logger.info(f"站点统计数据更新完成，日期: {date_str}")
            
        except Exception as e:
            db.session.rollback()
            app.logger.error(f"更新站点统计数据失败: {str(e)}")
            raise
